package top.heue.temp.data

import com.orhanobut.hawk.storage.Storage
import com.orhanobut.hawk.util.HawkUtils
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
import top.heue.utils.data.other.DH

@Entity
data class HawkData(
    @Id
    var id: Long = 0,
    @Index
    var key: String,
    var value: String
)

class HawkStorage : Storage {
    override fun <T : Any?> put(key: String?, value: T): Boolean {
        HawkUtils.checkNull("key", key)
        val data = DH.findOneOrNull(HawkData_.key to key!!)?.apply {
            this.value = value.toString()
        } ?: HawkData(key = key, value = value.toString())
        DH.addOrSet(data)
        return true
    }

    @Suppress("UNCHECKED_CAST")
    override fun <T : Any?> get(key: String?): T? {
        HawkUtils.checkNull("key", key)
        return DH.findOneOrNull(HawkData_.key to key!!)?.value as T?
    }

    override fun delete(key: String?): Boolean {
        HawkUtils.checkNull("key", key)
        DH.findOneOrNull(HawkData_.key to key!!)?.let {
            DH.removeById<HawkData>(it.id)
        }
        return true
    }

    override fun deleteAll(): Boolean {
        DH.removeAll<HawkData>()
        return true
    }

    override fun count(): Long {
        return DH.findAll<HawkData>().size.toLong()
    }

    //选择只是针对于文件存储提高性能
    override fun select(name: String?): Storage {
        return this
    }

    override fun contains(key: String?): Boolean {
        HawkUtils.checkNull("key", key)
        return DH.findOneOrNull(HawkData_.key to key!!) != null
    }

    override fun destroy() {}
}